package com.excilys.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.excilys.dao.IAccountDAO;
import com.excilys.model.Account;
import com.excilys.model.IllegalAccesException;
import com.excilys.model.User;
import com.excilys.utils.UserUtils;

/**
 * Class that implements services related to users.
 * 
 * @author excilys dev : SC
 * 
 */

@Service
@Transactional(readOnly = true)
public class AccountService {

	@Autowired
	private IAccountDAO myAccountDAO;

	public IAccountDAO getMyAccountDAO() {
		return myAccountDAO;
	}

	public void setMyAccountDAO(IAccountDAO myAccountDAO) {
		this.myAccountDAO = myAccountDAO;
	}

	public Account getAccountById(long accountId) {

		User currentUser = UserUtils.getConnectedUser();
		if (!checkAccountOwnByUser(accountId, currentUser)) {
			throw new IllegalAccesException();
		}
		return myAccountDAO.getAccountById(accountId);
	}

	/**
	 * getAccountByNameSecured which verify that currentUser own the account.
	 */

	public Account getAccountByNameSecured(String accountName) {
		User currentUser = UserUtils.getConnectedUser();
		if (!checkAccountOwnByUser(accountName, currentUser)) {
			throw new IllegalAccesException();
		}
		return myAccountDAO.getAccountByName(accountName);
	}

	/**
	 * getAccountByNameSecured which not verify that currentUser own the account.
	 */
	public Account getAccountByNameNotSecured(String accountName) {
		return myAccountDAO.getAccountByName(accountName);
	}

	/**
	 * Check that user is the owner of the wanted account
	 */
	private boolean checkAccountOwnByUser(String accountName, User currentUser) {
		return currentUser.containAccountOfName(accountName);
	}

	/**
	 * Check that user is the owner of the wanted account
	 */
	private boolean checkAccountOwnByUser(long accountId, User currentUser) {
		return currentUser.containAccountOfId(accountId);
	}

}
